package com.cskaoyan.controller;

import com.cskaoyan.bean.Admin;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.InfoBean;
import com.cskaoyan.service.AdminLoginService;
import com.cskaoyan.shiro.MallToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;


@RestController
@RequestMapping("admin/auth")
public class AdminAuthController {

    @Autowired
    AdminLoginService adminLoginService;
    /*
     * 认证
     * */
    @PostMapping("login")
    public BaseRespVo adminLogin(@RequestBody Map map, HttpServletRequest request){
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        if(username == null || password == null){
            return BaseRespVo.fail();
        }
        MallToken mallToken = new MallToken(username, password, "admin");
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(mallToken);
        } catch (AuthenticationException e) {
            // e.printStackTrace();
            return BaseRespVo.fail();
        }

        // 登陆成功，更新admin表
        String name = (String) subject.getPrincipal();
        Admin admin = new Admin();
        admin.setUsername(name);
        admin.setLastLoginTime(new Date());
        admin.setLastLoginIp(request.getLocalAddr());
        admin.setPassword(null); //避免错误地更新密码
        adminLoginService.update(admin);

        Serializable id = subject.getSession().getId();
        return BaseRespVo.ok(id);
    }

    @RequestMapping("logout")
    public BaseRespVo logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }

    @RequestMapping("info")
    public BaseRespVo info(String token){
        Admin admin = new Admin();
        String name = (String) SecurityUtils.getSubject().getPrincipal();
        admin.setUsername(name);
        InfoBean info = adminLoginService.getLoginInfo(admin);
        return BaseRespVo.ok(info);
    }

//
//    @RequestMapping("wx/login")
//    public void wxLogin(String username, String password){
//        MallToken wxToken = new MallToken(username, password, "wx");
//        Subject subject = SecurityUtils.getSubject();
//        subject.login(wxToken);
//    }


}
